package com.jsgt.greekfire.ui.mainassets

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.text.TextUtils
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.fhx.core.base.BaseActivity
import com.fhx.core.scan.android.CaptureActivity
import com.fhx.core.utils.ToastUtils
import com.ftd.livepermissions.LivePermissions
import com.ftd.livepermissions.PermissionResult
import com.jsgt.greekfire.BuildConfig
import com.jsgt.greekfire.R
import com.jsgt.greekfire.WALLET_ADDRESS
import com.jsgt.greekfire.ZERO_COMPARE
import com.jsgt.greekfire.bean.AddressBean
import com.jsgt.greekfire.dialog.SecurityPwdDialog
import com.jsgt.greekfire.event.TransferEvent
import com.jsgt.greekfire.factory.CoinViewModelFactory
import com.jsgt.greekfire.ui.mainassets.adapter.CurrencyListActivity
import com.jsgt.greekfire.ui.mine.coindetail.transfer.TransferActivity
import com.jsgt.greekfire.ui.mine.user.address.AddressActivity
import com.jsgt.greekfire.viewmodel.CoinViewModel
import kotlinx.android.synthetic.main.activity_new_transfer.*
import org.greenrobot.eventbus.EventBus

class NewTransferActivity : BaseActivity() {
    private var currency: String? = null
    private var accountNum: String? = null
    private var currentSymbol: String? = null
    private var assetGuid: String? = null
    private var assetBalance: Double? = null
    private val REQUEST_CURRENCY = 101
    private val REQUEST_CODE = 1001
    private val REQUEST_CODE_SCAN = 1002
    private val ADDRESS_BEAN = "address_bean"
    private val ASSETS_BEAN = "bean"
    private val DECODED_CONTENT_KEY = "codedContent"
    private var pwdDialog: SecurityPwdDialog? = null
    private var glbCharge = 0.0//扣除管理费金额
    private var addressBean: AddressBean? = null
    private val coinViewModel: CoinViewModel by lazy {
        ViewModelProvider(
            this,
            CoinViewModelFactory()
        ).get(CoinViewModel::class.java)
    }

    override fun getLayoutId(): Int = R.layout.activity_new_transfer

    override fun main() {
        currentSymbol = intent.getStringExtra("symbol")
        assetGuid = intent.getStringExtra("assetGuid")
        assetBalance = intent.getDoubleExtra("assetBalance", 0.00)
        if (!TextUtils.isEmpty(currentSymbol)) {
            tvCurrency.setText(currentSymbol)
        }
        title = resources.getString(R.string.transfer_title)
        var scan_iv = setRightImage(R.mipmap.icon_scan)
        scan_iv.setOnClickListener {
            LivePermissions(this).request(
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA
            ).observe(this, Observer {
                when (it) {
                    is PermissionResult.Grant -> {
                        startActivityForResult(
                            Intent(this, CaptureActivity::class.java),
                            REQUEST_CODE_SCAN
                        )
                    }
                    is PermissionResult.Rationale -> {

                    }
                    is PermissionResult.Deny -> {
                        ToastUtils.show(this, "权限拒绝")
                    }
                }
            })
        }
        scan_iv.setColorFilter(ContextCompat.getColor(this, R.color.address_text))

        btnTransfers.setOnClickListener {
            currency = tvCurrency.text.toString().trim()
            accountNum = etAccountNum.text.toString().trim()
            if (TextUtils.isEmpty(currency)) {
                showToast(resources.getString(R.string.transfer_currency_select))
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(accountNum)) {
                showToast(resources.getString(R.string.transfer_num_hint))
                return@setOnClickListener
            }
            val num = etAccountNum.text.toString().trim()
            showDialog(num)
        }
        tvSelectCurrency.setOnClickListener {
            var intent = Intent(this, CurrencyListActivity::class.java)
            startActivityForResult(intent, REQUEST_CURRENCY)
        }

        coinViewModel.getManagerCharge("1,2")
        coinViewModel.managerChargeLiveData.observe(this, Observer {
            for (i in it) {
                //管理币
                if (TextUtils.equals("1", assetGuid!!)) {
                    glbCharge = i.price!!.toDouble()
                    tvLimitNum.setText("当前扣除" + currentSymbol + i.price)
                }
            }
        })
        coinViewModel.transferLiveData.observe(this, Observer {

            ToastUtils.show(this, "提交成功")
            showProgress(false)
            val num = etAccountNum.text.toString().trim()
            var sum = num.toDouble()
            if (TextUtils.equals("1", assetGuid) && assetBalance!! > glbCharge) {
                //如果是管理币页面，则多扣0.1管理费
                sum = num.toDouble().plus(glbCharge)
            }
            EventBus.getDefault().post(TransferEvent("$sum"))
            finish()
        })
        coinViewModel.errorLiveData.observe(this, Observer {
            showProgress(false)
        })
        address_book_iv.setOnClickListener {
            AddressActivity.start(
                this, AddressActivity.TRANSFER,
                REQUEST_CODE
            )
        }

    }

    private fun showDialog(num: String) {
        if (TextUtils.isEmpty(num)) {
            ToastUtils.show(this, "数量不能为空")
            return
        }
        if (num.toDouble() < ZERO_COMPARE) {
            ToastUtils.show(this, "金额必须大于0")
            return
        }
        val address = etAccountName.text.toString()
        if (TextUtils.isEmpty(address)) {
            ToastUtils.show(this, "地址不能为空")
            return
        }

        if (TextUtils.equals(address, WALLET_ADDRESS)) {
            ToastUtils.show(this, "不能给自己转账")
            return
        }

        if (!address.startsWith(BuildConfig.WALLET_PRIVATE_KEY_START) || address.length != 36) {
            ToastUtils.show(this, "转账地址有误")
            return
        }

        initDialog()
        pwdDialog?.nameTv!!.text = currentSymbol
        pwdDialog?.numberTv!!.text = num
        pwdDialog?.show()

    }

    private fun initDialog() {
        pwdDialog = SecurityPwdDialog(mContext!!, R.style.dialog)
        pwdDialog?.inputCallback = object : SecurityPwdDialog.InputCallback {
            override fun callBack(result: String) {
                transfer(result)
            }
        }
    }

    private fun transfer(pwd: String) {
        val num = etAccountNum.text.toString().trim()
        val address = etAccountName.text.toString()
        showProgress(true)

        coinViewModel.transferToAddress(
            num,
            assetGuid!!,
            address, pwd
        )
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                REQUEST_CURRENCY -> {
                    coinViewModel.getManagerCharge("1,2")
                    currentSymbol = data!!.getStringExtra("currentSymbol")
                    assetGuid = data!!.getStringExtra("assetGuid")
                    assetBalance = data!!.getDoubleExtra("assetBalance", 0.00)
                    if (!TextUtils.isEmpty(currentSymbol)) {
                        tvCurrency.setText(currentSymbol)
                    }
                }
                REQUEST_CODE_SCAN -> {
                    val content = data?.getStringExtra(DECODED_CONTENT_KEY)
                    etAccountName.setText(content)
                }
                REQUEST_CODE -> {
                    addressBean = data!!.getParcelableExtra(TransferActivity.ADDRESS_BEAN)
                    etAccountName.setText(addressBean!!.addr)
                }
            }

        }
    }

    override fun onDestroy() {
        super.onDestroy()
        pwdDialog = null
    }
}